/*
 *所有关于Blank_Grade_Concession_warn类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Blank_Grade_Concession_warnService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.DbSqlSugar;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Mvc;
using DGZImp.Core.BaseInterface;
using System.Security.AccessControl;

namespace ATkg.BizAppProject.Services
{
    public partial class Blank_Grade_Concession_warnService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBlank_Grade_Concession_warnRepository _repository;//访问数据库
        private readonly AmesSyncService _amesSyncService;

        [ActivatorUtilitiesConstructor]
        public Blank_Grade_Concession_warnService(
            IBlank_Grade_Concession_warnRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            AmesSyncService amesSyncService
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _amesSyncService = amesSyncService ?? throw new ArgumentNullException(nameof(amesSyncService));

            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public async Task<object> GetDataFromMes()
        {
            // 获取当天日期
            DateTime today = DateTime.Today;
            // 计算前两天日期
            DateTime twoDaysAgo = today.AddDays(-2);
            // 格式化日期为字符串（与你的示例格式一致）
            string twoDaysAgoStr = twoDaysAgo.ToString("yyyy-MM-dd");
            string todayStr = today.ToString("yyyy-MM-dd");

            var qDomain = new List<object>
            {
                "&", // AND 条件
                new List<object> { "insp_quality_state", "=", "inside_pass" },
                new List<object> { "partner_id", "ilike", "压型" },
                new List<object> { "inspection_time", ">", twoDaysAgoStr  },
                new List<object> { "inspection_time", "<", todayStr }
            };
            var qFields = new List<string> {
                "blank_name",
                "product_id",
                "br_normal",
                "hcj_normal",
                "partner_id",
                "inspection_time",
                "insp_quality_state",
                "spec_bh_lines",
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
            };
            var resp = await _amesSyncService.CallSearchReadBH("atm.qc.inspect.bh", qDomain, qFields, qPage);
            var res = (JArray)resp["result"];
            var r = new List<Blank_Grade_Concession_warn>();


            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                // 通过更详细的id获取常温-br hcj标准值
                var br_standard = "";
                var hcj_standard = "";
                var spec_bh_lines_ids = x["spec_bh_lines"];
                if (spec_bh_lines_ids is JArray linesArray && linesArray.Count > 0)
                {
                    foreach (var line in linesArray)
                    {
                        // 处理每个 line 项
                        Console.WriteLine(line.ToString());
                        var id = (int)(line);

                        var qDomain2 = new List<object>
                        {
                            id
                        };
                        var qFields2 = new List<string>
                        {
                            "name",
                            "br",
                            "hcj"
                        };
                        var resp2 = await _amesSyncService.CallRead("atm.qc.inspect.bh.spec.line", qDomain2, qFields2, qPage);
                        var res2 = (JArray)resp2["result"];
                        var y = (JObject)res2[0];
                        var name = (string)y["name"];
                        if (name == "常温")
                        {
                            br_standard = (string)y["br"];
                            hcj_standard = (string)y["hcj"];
                            break;
                        }
                    }
                }
                // 通过产品代码获取-br hcj让步值
                var br_concession = "";
                var hcj_concession = "";
                var productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString() : "";
                //var productId = "S-5115A/毛坯";
                var qDomain3 = new List<object>{
                        new List<object> { "product_id", "=", productId},
                    };
                var qFields3 = new List<string> {
                        "lines"
                    };
                var resp3 = await _amesSyncService.CallSearchReadBH("atm.qc.inspect.subspec.bh", qDomain3, qFields3, qPage);
                // 为空判断++++++++++++++++++++++++++++++++++
                if (resp3?["result"] is JArray res3 && res3.Count > 0)
                {
                    var z = res3[0] as JObject;
                    var concession_bh_lines_ids = z?["lines"];

                    if (concession_bh_lines_ids is JArray concession_linesArray && concession_linesArray.Count > 0)
                    {
                        foreach (var concession_line in concession_linesArray)
                        {
                            // 处理每个 line 项
                            Console.WriteLine(concession_line.ToString());
                            var concession_id = (int)concession_line;

                            var qDomain4 = new List<object> { concession_id };
                            var qFields4 = new List<string> { "name", "br", "hcj" };
                            var resp4 = await _amesSyncService.CallRead("atm.qc.inspect.bh.spec.line", qDomain4, qFields4, qPage);

                            // 添加 resp4 空判断
                            if (resp4?["result"] is not JArray res4 || res4.Count == 0)
                            {
                                continue; // 如果resp4为空，跳过当前循环，继续下一个
                            }

                            var zz = res4[0] as JObject;
                            if (zz == null) continue;

                            var concession_name = zz["name"]?.ToString();
                            if (concession_name == "常温")
                            {
                                br_concession = zz["br"]?.ToString() ?? "";
                                hcj_concession = zz["hcj"]?.ToString() ?? "";
                                break;
                            }
                        }
                    }
                }



                r.Add(new Blank_Grade_Concession_warn
                {
                    //ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = productId,
                    BlankLotName = (string)x["blank_name"],
                    BrReal = decimal.Round((decimal)x["br_normal"], 2),
                    HcjReal = decimal.Round((decimal)x["hcj_normal"], 2),
                    InspectionTime = ((DateTime)x["inspection_time"]),
                    QualityStatus = "通过2",
                    BrStandard = (string)br_standard,
                    HcjStandard = (string)hcj_standard,
                    BrConcession = (string)br_concession,
                    HcjConcession = (string)hcj_concession,
                    IsWarn = "否"
                }); ; ;
            }
            await Db.DoInsertAsync<Blank_Grade_Concession_warn>(r);

            return new { Success = true, Message = "处理成功" };
        }

        public async Task<object> GetDataFromDbAndDeal()
        {
            try
            {
                // 1. 查询数据库数据 - 异常处理
                List<Blank_Grade_Concession_warn> result = null;
                try
                {
                    result = await Db.Queryable<Blank_Grade_Concession_warn>()
                        .Where(x => x.IsWarn == "否")
                        .ToListAsync();

                    if (result == null)
                    {
                        return new { Success = false, Message = "数据库查询结果为空", ErrorCode = "DB_QUERY_NULL" };
                    }
                }
                catch (Exception ex)
                {
                    return new { Success = false, Message = $"数据库查询失败：{ex.Message}", ErrorCode = "DB_QUERY_ERROR", Exception = ex.ToString() };
                }

                // 2. 数据分组处理 - 空值判断
                if (!result.Any())
                {
                    return new { Success = true, Message = "当前没有预警状态为'否'的信息", ErrorCode = "NO_DATA" };
                }

                var duplicateGroups = result
                    .Where(inspection => inspection.InspectionTime.HasValue)
                    ?.GroupBy(inspection => new
                    {
                        ProductId = inspection.ProductId,
                        Year = inspection.InspectionTime.Value.Year,
                        Month = inspection.InspectionTime.Value.Month
                    })
                    ?.Where(group => group.Count() >= 2)
                    ?.ToList();

                // 检查分组结果
                if (duplicateGroups == null || !duplicateGroups.Any())
                {
                    return new { Success = true, Message = "处理成功，未发现通过2状态出现2次及以上的记录", ErrorCode = "NO_DUPLICATES" };
                }

                var duplicateRecords = duplicateGroups.SelectMany(group => group)?.ToList();

                if (duplicateRecords == null || !duplicateRecords.Any())
                {
                    return new { Success = true, Message = "处理成功，未发现重复记录", ErrorCode = "NO_DUPLICATE_RECORDS" };
                }

                // 3. 更新数据库操作 - 异常处理
                try
                {
                    var idsToUpdate = duplicateRecords.Select(record => record.Id).ToList();

                    if (idsToUpdate == null || !idsToUpdate.Any())
                    {
                        return new { Success = false, Message = "没有需要更新的记录ID", ErrorCode = "NO_IDS_TO_UPDATE" };
                    }

                    var recordsToUpdate = await Db.Queryable<Blank_Grade_Concession_warn>()
                        .Where(x => idsToUpdate.Contains(x.Id))
                        .ToListAsync();

                    if (recordsToUpdate == null || !recordsToUpdate.Any())
                    {
                        return new { Success = false, Message = "未找到需要更新的记录", ErrorCode = "RECORDS_TO_UPDATE_NOT_FOUND" };
                    }

                    recordsToUpdate.ForEach(record => record.IsWarn = "是");
                    var updateResult = await Db.DoUpdateAsync(recordsToUpdate);

                    // 检查更新结果（根据DoUpdateAsync的返回值类型调整）
                    if (updateResult <= 0)
                    {
                        return new { Success = false, Message = "数据库更新操作未影响任何记录", ErrorCode = "UPDATE_NO_EFFECT" };
                    }
                }
                catch (Exception ex)
                {
                    return new { Success = false, Message = $"数据库更新失败：{ex.Message}", ErrorCode = "DB_UPDATE_ERROR", Exception = ex.ToString() };
                }

                // 4. 合并记录处理
                var mergedGroups = duplicateRecords
                    ?.GroupBy(record => new { record.ProductId })
                    ?.Where(group => group.Count() > 1)
                    ?.ToList();

                if (mergedGroups == null || !mergedGroups.Any())
                {
                    // 如果没有需要合并的组，跳过邮件发送
                    return new { Success = true, Message = "数据库更新成功，无需要发送邮件的记录", ErrorCode = "NO_MERGED_GROUPS" };
                }

                var mergedRecords = new List<Blank_Grade_Concession_warn>();
                foreach (var group in duplicateGroups)
                {
                    var groupRecords = group?.ToList();

                    if (groupRecords == null || !groupRecords.Any())
                    {
                        continue; // 跳过空组
                    }

                    if (groupRecords.Count == 2)
                    {
                        // 检查BlankLotName是否为空
                        groupRecords[0].BlankLotName = MergeBlankLotNames(
                            groupRecords[0]?.BlankLotName,
                            groupRecords[1]?.BlankLotName);
                        mergedRecords.Add(groupRecords[0]);
                    }
                    else
                    {
                        var firstRecord = groupRecords.FirstOrDefault();
                        if (firstRecord == null) continue;

                        for (int i = 1; i < groupRecords.Count; i++)
                        {
                            firstRecord.BlankLotName = MergeBlankLotNames(
                                firstRecord?.BlankLotName,
                                groupRecords[i]?.BlankLotName);
                        }
                        mergedRecords.Add(firstRecord);
                    }
                }

                if (mergedRecords == null || !mergedRecords.Any())
                {
                    return new { Success = false, Message = "合并记录失败，没有生成合并后的记录", ErrorCode = "MERGE_RECORDS_FAILED" };
                }

                // 5. 邮件发送处理
                try
                {
                    for (int i = 0; i < mergedRecords.Count(); i++)
                    {
                        var record = mergedRecords[i];

                        // 检查record是否为空
                        if (record == null)
                        {
                            continue; // 或记录错误并继续
                        }

                        // 产品ID处理
                        var productId = !string.IsNullOrEmpty(record.ProductId) && record.ProductId.Contains('/')
                            ? record.ProductId.Split('/')[0]
                            : record.ProductId;

                        if (string.IsNullOrEmpty(productId))
                        {
                            // 记录错误并继续处理下一条
                            continue;
                        }

                        var blankLotName = record.BlankLotName;

                        // 获取客户代码
                        List<object> partnerIds = null;
                        try
                        {
                            partnerIds = (List<object>)await _amesSyncService.SyncProductionPartnerName(productId);
                        }
                        catch (Exception ex)
                        {
                            // 记录错误并继续
                            continue;
                        }

                        if (partnerIds == null || !partnerIds.Any())
                        {
                            // 发送默认邮件通知
                            await _amesSyncService.SendEmailAsync(
                                "quanwei@atmcn.com",
                                "材料性能质量预警",
                                $"材料性能质量预警:,{productId}产品,未获取到客户代码，{blankLotName},当前质量状态通过2，低于预期目标");
                            continue;
                        }

                        List<object> email_list = new List<object>();
                        foreach (var partnerId in partnerIds)
                        {
                            if (partnerId == null) continue;

                            string partnerName = partnerId.ToString();
                            Email_Warn_Kg_Pinguan emailWarn = null;

                            try
                            {
                                emailWarn = (Email_Warn_Kg_Pinguan)await SyncPartnerEmailInfo(partnerName);
                            }
                            catch (Exception ex)
                            {
                                // 记录错误并使用默认邮箱
                                email_list.Add("renyupeng@atmcn.com");
                                email_list.Add("gnchenjie@atmcn.com");
                                continue;
                            }

                            if (emailWarn == null)
                            {
                                await _amesSyncService.SendEmailAsync(
                                    "quanwei@atmcn.com",
                                    "材料性能质量预警",
                                    $"材料性能质量预警:,{productId}产品,对应客户代码在磁云平台未维护邮箱，请注意！{blankLotName},当前质量状态通过2，低于预期目标");
                                email_list.Add("renyupeng@atmcn.com");
                                email_list.Add("gnchenjie@atmcn.com");
                            }
                            else
                            {
                                // 检查邮箱字段是否为空
                                if (!string.IsNullOrEmpty(emailWarn.ManagerEmail))
                                    email_list.Add(emailWarn.ManagerEmail);
                                if (!string.IsNullOrEmpty(emailWarn.QualityEmail))
                                    email_list.Add(emailWarn.QualityEmail);
                                if (!string.IsNullOrEmpty(emailWarn.TechEmail))
                                    email_list.Add(emailWarn.TechEmail);
                                email_list.Add("renyupeng@atmcn.com");
                                email_list.Add("gnchenjie@atmcn.com");
                            }
                        }

                        var uniqueEmails = email_list?.Distinct()?.ToList();

                        if (uniqueEmails == null || !uniqueEmails.Any())
                        {
                            // 没有有效邮箱，发送默认通知
                            await _amesSyncService.SendEmailAsync(
                                "quanwei@atmcn.com",
                                "材料性能质量预警",
                                $"材料性能质量预警:,{productId}产品,{blankLotName},无有效接收邮箱");
                            continue;
                        }

                        foreach (var item in uniqueEmails)
                        {
                            if (item == null || string.IsNullOrEmpty(item.ToString()))
                                continue;

                            try
                            {
                                await _amesSyncService.SendEmailAsync(
                                    item.ToString(),
                                    "材料性能质量预警",
                                    $"材料性能质量预警:,{productId}产品,{blankLotName},当前质量状态通过2，低于预期目标，连续出现低标准毛坯，请及时登录磁云平台和MES确认，查找原因并改善。");
                            }
                            catch (Exception ex)
                            {
                                // 单个邮件发送失败不影响整体流程，记录错误继续
                                Console.WriteLine($"发送邮件到{item}失败：{ex.Message}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 邮件发送环节的整体异常
                    return new
                    {
                        Success = false,
                        Message = $"邮件发送过程中出现错误：{ex.Message}",
                        ErrorCode = "EMAIL_SEND_ERROR",
                        Exception = ex.ToString(),
                        Detail = "数据库更新已完成，但邮件发送环节出错"
                    };
                }

                return new { Success = true, Message = "处理成功，数据库已更新并发送邮件通知", ErrorCode = "SUCCESS" };
            }
            catch (Exception ex)
            {
                // 全局异常捕获
                return new
                {
                    Success = false,
                    Message = $"系统异常：{ex.Message}",
                    ErrorCode = "SYSTEM_ERROR",
                    Exception = ex.ToString(),
                    StackTrace = ex.StackTrace
                };
            }
        }
        /// <summary>
        /// 合并BlankLotName字段
        /// </summary>
        private string MergeBlankLotNames(string original, string toMerge)
        {
            if (string.IsNullOrEmpty(original))
                return toMerge;

            if (string.IsNullOrEmpty(toMerge))
                return original;

            // 拆分并去重
            var lotNames = original.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries)
                .Concat(toMerge.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries))
                .Select(lot => lot.Trim())
                .Distinct()
                .ToList();

            return string.Join(", ", lotNames);
        }

        public async Task<object> GetDateFromDb()
        {

            var latestData = await Db.Set<Blank_Grade_Concession_warn>()
                .Where(x => x.IsValid == 1)
                .OrderByDescending(x => x.CreateTime) // 按日期降序排序
                .FirstOrDefaultAsync();
            return latestData == null ? "暂无数据" : latestData.CreateTime.ToString();
        }

        public async Task<object> SyncPartnerEmailInfo(string name)
        {
            var Data = await Db.Set<Email_Warn_Kg_Pinguan>().Where(x => x.PartnerId == name)
                .FirstAsync();
            return Data;
        }
    }
}
